Understanding common pitfalls is key to writing robust traversal code.

  • Forgetting to use a visited set is the most common error, often leading to infinite loops in graphs with cycles.
  • Using the wrong data structure (queue vs. stack) will produce a valid traversal, but it won't be the one you intended (BFS vs. DFS).
  • Applying BFS for shortest paths on weighted graphs will give incorrect results. BFS only works when all edge weights are uniform (e.g., 1).
  • Debugging Tip: Print the contents of your queue/stack at each step, and log which node is being visited. This makes the algorithm's behavior transparent.
Debugging Checklist
Mistake Symptom Diagnostic
No `visited` set Infinite loop, repeated node visits Log every node visit; check for duplicates
Wrong Data Structure Incorrect traversal order Log queue/stack state; assert FIFO/LIFO
BFS on Weighted Graph Wrong shortest path distances Use Dijkstra's algorithm instead